package com.heima.wemedia.filter;

import com.heima.wemedia.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //定义无需过滤的请求
        List<String> urlList = Arrays.asList(
                "/v2/api-docs",
                "/login/in"
        );
        //获取请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //判断当前是否是登录请求，如果是登录则放行
        String reqUrl = request.getURI().getPath();
        for (String url : urlList) {
            if (reqUrl.contains(url)) {
                return chain.filter(exchange);
            }
        }
        //获取请求头jwt token信息
        String token = request.getHeaders().getFirst("token");
        //判断token是否存在
        if (StringUtils.isBlank(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //验证token是否有效
        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int verifyToken = AppJwtUtil.verifyToken(claims);
            //-1 0 有效，1 2 失效
            if (verifyToken > 0){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //将用户id设置到请求头中 ，将令牌信息传递到各个微服务
            Integer id = claims.get("id", Integer.class);
            ServerHttpRequest serverHttpRequest = request.mutate().headers(HttpHeaders->{
                HttpHeaders.add("useId",String.valueOf(id));
            }).build();
            exchange.mutate().request(serverHttpRequest).build();
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
